 package com.warrior.superdata.dds.esclient;


 import com.warrior.superdata.dds.domain.DBVo;
 import lombok.Data;
 import org.apache.http.HttpHost;
 import org.apache.http.auth.AuthScope;
 import org.apache.http.auth.UsernamePasswordCredentials;
 import org.apache.http.client.CredentialsProvider;
 import org.apache.http.impl.client.BasicCredentialsProvider;
 import org.apache.http.impl.nio.client.HttpAsyncClientBuilder;
 import org.apache.logging.log4j.util.Strings;
 import org.elasticsearch.client.RestClient;
 import org.elasticsearch.client.RestClientBuilder;
 import org.elasticsearch.client.RestHighLevelClient;

 @Data
 class ElasticsearchRestClient {

     private RestClientBuilder restClientBuilder;

     private RestHighLevelClient restHighLevelClient;

     public void restClientBuilder(DBVo dbDto) {
         if(null == restClientBuilder){
             final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
             //es账号密码（默认用户名为elastic）
             credentialsProvider.setCredentials(AuthScope.ANY,
                     new UsernamePasswordCredentials(dbDto.getUsername(), dbDto.getPassword()));
             HttpHost httpHost = new HttpHost(dbDto.getIp(), Integer.valueOf(dbDto.getPort()), HttpHost.DEFAULT_SCHEME_NAME);
             RestClientBuilder restClientBuilder = RestClient.builder(httpHost);
             if(Strings.isNotBlank(dbDto.getUsername())){
                 // 如果需要验证则需要获取用户名和密码
                 restClientBuilder = restClientBuilder.setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {
                     @Override
                     public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpAsyncClientBuilder) {
                         httpAsyncClientBuilder.disableAuthCaching();
                         return httpAsyncClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
                     }
                 });
             }
             this.restClientBuilder = restClientBuilder;
             this.restHighLevelClient = new RestHighLevelClient(restClientBuilder);
         }
     }


 }

